<template>
    <div>
        <!-- 搜索栏 -->
        <div class="card" style="margin-bottom: 5px">
            <el-input style="width: 240px; margin-right: 10px" v-model="data.name" placeholder="请输入酒店名称查询"
                prefix-icon="Search"></el-input>
            <el-button type="primary" @click="load">查 询</el-button>
            <el-button type="warning" @click="reset">重 置</el-button>
        </div>

        <!-- 操作按钮 -->
        <div class="card" style="margin-bottom: 5px">
            <el-button type="primary" @click="handleAdd">新 增</el-button>
            <el-button type="danger" @click="delBatch">批量删除</el-button>
        </div>

        <!-- 数据表格 -->
        <div class="card" style="margin-bottom: 5px">
            <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="酒店名称" prop="name" />
                <el-table-column label="地址" prop="address" show-overflow-tooltip />
                <el-table-column label="星级" prop="starRating" />
                <el-table-column label="描述" prop="description" show-overflow-tooltip />
                <el-table-column label="创建时间" prop="createTime" />
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" circle></el-button>
                        <el-button @click="del(scope.row.id)" type="danger" :icon="Delete" circle></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div style="margin-top: 15px">
                <el-pagination @size-change="load" @current-change="load" v-model:current-page="data.pageNum"
                    v-model:page-size="data.pageSize" :page-sizes="[5, 10, 15, 20]" background
                    layout="total, sizes, prev, pager, next, jumper" :total="data.total" />
            </div>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog title="酒店信息" v-model="data.formVisible" width="500px" destroy-on-close>
            <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="80px"
                style="padding: 20px 40px 0 0">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入酒店名称" />
                </el-form-item>

                <el-form-item label="地址" prop="address">
                    <el-input v-model="data.form.address" autocomplete="off" placeholder="请输入酒店地址" />
                </el-form-item>

                <el-form-item label="星级" prop="starRating">
                    <el-input-number v-model="data.form.starRating" :min="1" :max="5" placeholder="请输入星级（1-5）" />
                </el-form-item>

                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" :rows="3" v-model="data.form.description" placeholder="请输入酒店描述" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="data.formVisible = false">取 消</el-button>
                    <el-button type="primary" @click="save">保 存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { Edit, Delete, Search } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";

// 初始化数据状态
const data = reactive({
    name: null,          // 搜索条件：酒店名称
    tableData: [],       // 表格数据
    pageNum: 1,          // 当前页码
    pageSize: 10,        // 每页数量
    total: 0,            // 总记录数
    formVisible: false,  // 对话框可见性
    form: {},            // 表单数据
    ids: [],             // 选中的ID列表
    rules: {             // 表单校验规则
        name: [{ required: true, message: '请输入酒店名称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入酒店地址', trigger: 'blur' }],
        starRating: [{ required: true, message: '请输入星级', trigger: 'blur' }]
    }
});

const formRef = ref();  // 表单引用

// 加载数据（分页查询）
const load = () => {
    request.get('/hotel/selectPage', {
        params: {
            pageNum: data.pageNum,
            pageSize: data.pageSize,
            name: data.name  // 传递搜索条件到后端
        }
    }).then(res => {
        data.tableData = res.data.list;
        data.total = res.data.total;
    });
};
load();  // 初始化加载

// 重置搜索条件
const reset = () => {
    data.name = null;
    load();
};

// 新增酒店
const handleAdd = () => {
    data.formVisible = true;
    data.form = {};  // 清空表单
};

// 保存（新增/编辑）
const save = () => {
    formRef.value.validate(valid => {
        if (!valid) return;
        data.form.id ? update() : add();
    });
};

// 新增提交
const add = () => {
    request.post('/hotel/add', data.form).then(res => {
        if (res.code === '200') {
            data.formVisible = false;
            ElMessage.success('新增成功');
            load();  // 刷新数据
        } else {
            ElMessage.error(res.msg);
        }
    });
};

// 编辑酒店
const handleUpdate = (row) => {
    data.form = JSON.parse(JSON.stringify(row));  // 深拷贝避免影响原数据
    data.formVisible = true;
};

// 编辑提交
const update = () => {
    request.put('/hotel/update', data.form).then(res => {
        if (res.code === '200') {
            data.formVisible = false;
            ElMessage.success('更新成功');
            load();  // 刷新数据
        } else {
            ElMessage.error(res.msg);
        }
    });
};

// 单条删除
const del = (id) => {
    ElMessageBox.confirm('删除后无法恢复，确认删除？', '提示', { type: 'warning' })
        .then(() => {
            request.delete(`/hotel/deleteById/${id}`).then(res => {
                if (res.code === '200') {
                    ElMessage.success('删除成功');
                    load();  // 刷新数据
                } else {
                    ElMessage.error(res.msg);
                }
            });
        });
};

// 批量删除
const delBatch = () => {
    if (data.ids.length === 0) {
        ElMessage.warning('请选择要删除的酒店');
        return;
    }
    ElMessageBox.confirm('删除后无法恢复，确认删除？', '提示', { type: 'warning' })
        .then(() => {
            request.delete('/hotel/deleteBatch', { data: data.ids }).then(res => {
                if (res.code === '200') {
                    ElMessage.success('批量删除成功');
                    load();  // 刷新数据
                } else {
                    ElMessage.error(res.msg);
                }
            });
        });
};

// 处理表格选中项
const handleSelectionChange = (rows) => {
    data.ids = rows.map(row => row.id);
};
</script>

<style scoped>
/* 可选样式调整 */
.el-table .el-table__cell {
    padding: 8px 0;
}
</style>